# This file is used to create a login blueprint for the flask application.
# The blueprint is used to handle the login functionality of the application.


from flask import Blueprint
from flask import request
from flask import jsonify
import psycopg2.extras
from settings import *
from database import PostgreSingleton
from database.wx_user_info_extend_methods import WxUserInfoExtendTableMethods
from database.wx_user_table_methods import WxUserTableMethods
from database.wx_authentication_aggregation_methods import WxAuthenticationAggregationMethods

import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

user_info_extend_blueprint = Blueprint('user_info_extend_blueprint', __name__)


# 查询注册人员总数
@user_info_extend_blueprint.route('/query_user_total_count')
def query_user_total_count():

    with PostgreSingleton() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries

        wtm = WxUserInfoExtendTableMethods(conn, cur)
        wx_user_info = wtm.query_user_total_count()

    result_body = {
        "status": 1,
        "errorCode": None,
        "errorMsg": None,
        "resultBody": wx_user_info
    }

    return jsonify(result_body)



# 查询 推荐用户信息
@user_info_extend_blueprint.route('/recommend_user_info')
def recommend_user_info():

    recommend_user_openid = request.args.get('recommend_user_id')

    with PostgreSingleton() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries

        wtm = WxUserTableMethods(conn, cur)
        wx_user_info = wtm.get_user_by_open_id(recommend_user_openid)

        if not wx_user_info:
            args_error = {
                "status": -1,
                "errorCode": 1002,
                "errorMsg": "User not found",
                "resultBody": None
            }

            return jsonify(args_error)

        recommend_user_id = wx_user_info["user_id"]


        wtm = WxUserInfoExtendTableMethods(conn, cur)
        wx_user_info = wtm.query_user_info_by_user_id(recommend_user_id)

    result_body = {
        "status": 1,
        "errorCode": None,
        "errorMsg": None,
        "resultBody": wx_user_info
    }

    return jsonify(result_body)

# 查询 自己的推荐用户所有信息
@user_info_extend_blueprint.route('/query_user_info_by_recommend_user_id')
def query_user_info_by_recommend_user_id():

    self_open_id = request.args.get('self_open_id')
    page = request.args.get('page', default=1, type=int)
    limit = request.args.get('limit', default=10, type=int)

    with PostgreSingleton() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries

        wtm = WxUserTableMethods(conn, cur)
        wx_user_info = wtm.get_user_by_open_id(self_open_id)

        if not wx_user_info:
            args_error = {
                "status": -1,
                "errorCode": 1002,
                "errorMsg": "User not found",
                "resultBody": None
            }

            return jsonify(args_error)

        recommend_user_id = wx_user_info["user_id"]


        wtm = WxUserInfoExtendTableMethods(conn, cur)
        wx_user_info = wtm.query_user_info_by_recommend_user_id(recommend_user_id, page, limit)

        for user_info in wx_user_info:

            wx_authentication_aggregation_methods = WxAuthenticationAggregationMethods(conn, cur)

            user_info["authentication_status"] = wx_authentication_aggregation_methods.get_wx_authentication_aggregation(user_info['user_id'])

    result_body = {
        "status": 1,
        "errorCode": None,
        "errorMsg": None,
        "resultBody": wx_user_info
    }

    return jsonify(result_body)




@user_info_extend_blueprint.route('/query_user_info_by_open_id')
def query_user_info_by_open_id():

    open_id = request.args.get('open_id')
    # Check if the required arguments are present
    if not open_id:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "open_id is required",
            "resultBody": None

        }

        return jsonify(args_error)

    # Check if the user exists in the database
    with PostgreSingleton() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries
        wtm = WxUserTableMethods(conn, cur)
        wx_user_info = wtm.get_user_by_open_id(open_id)

        if not wx_user_info:
            args_error = {
                "status": -1,
                "errorCode": 1002,
                "errorMsg": "User not found",
                "resultBody": None
            }

            return jsonify(args_error)
        
        wx_user_id = wx_user_info["user_id"]

        wui = WxUserInfoExtendTableMethods(conn, cur)
        wx_user_info_extend = wui.query_user_info_by_user_id(wx_user_id)

        recommend_user_view_data = wui.recommend_user_view_data(wx_user_id)

    result_body = {
        "status": 1,
        "errorCode": None,
        "errorMsg": None,
        "resultBody": {
            "user_id": wx_user_id,
            "wx_user_info": wx_user_info,
            "wx_user_info_extend": wx_user_info_extend,
            "recommend_user_view_data": recommend_user_view_data
        }
            
    }

    # 如果wx_user_info_extend["write_status"] == True，则表示用户已经填写过信息，可以直接返回信息,否则需要提示用户填写信息
    return jsonify(result_body)

# 个人基本信息 插入/升级
@user_info_extend_blueprint.route('/personal_base_info_insert', methods=['POST'])
def personal_base_info_insert():
    '''def base_info_insert(self, user_id, real_name, sex, e_mail, work_unit, job, city, province, address, department, phone_number, wx_id): # 基本信息插入'''

    open_id = request.form.get('open_id')
    real_name = request.form.get('real_name')
    sex = request.form.get('sex')
    e_mail = request.form.get('e_mail')
    work_unit = request.form.get('work_unit')
    job = request.form.get('job')
    city = request.form.get('city')
    province = request.form.get('province')
    address = request.form.get('address')
    department = request.form.get('department')
    phone_number = request.form.get('phone_number')

    # Check if the required arguments are present
    if not open_id or not real_name or not sex or not e_mail or not work_unit or not job or not city or not province or not address or not department or not phone_number:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "open_id, real_name, sex, e_mail, work_unit, job, city, province, address, department are required",
            "resultBody": None

        }

        return jsonify(args_error)
    
    # check phone_number format
    if not phone_number.isdigit() or len(phone_number)!= 11:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "phone_number format error",
            "resultBody": None

        }

        return jsonify(args_error)

    # Check if the user exists in the database
    with PostgreSingleton() as conn:




        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries
        wtm = WxUserTableMethods(conn, cur)

        wx_user_info = wtm.get_user_by_open_id(open_id)
        if not wx_user_info:
            args_error = {
                "status": -1,
                "errorCode": 1002,
                "errorMsg": "User not found",
                "resultBody": None
            }

            return jsonify(args_error)
        
        wx_user_id = wx_user_info["user_id"]

        wui = WxUserInfoExtendTableMethods(conn, cur)

        # 验证电话号码是否重复

        is_phone_number_exist = wui.query_phone_number_exist(phone_number)

        if is_phone_number_exist:
            args_error = {
                "status": -1,
                "errorCode": 1002,
                "errorMsg": "Phone number already exist",
                "resultBody": None
            }

            return jsonify(args_error)

        wui.base_info_insert(wx_user_id, real_name, sex, e_mail, work_unit, job, city, province, address, department, phone_number)

    result_body = {
        "status": 1,
        "errorCode": None,
        "errorMsg": None,
        "resultBody": "User info insert success"
            
    }

    return jsonify(result_body)

# # 工作信息插入及需求信息插入
#    def work_info_insert(self, user_id, unit_property, field, unit_introduction, competitive_strength, activity_city, resource, help, recommend_user_id, write_status=True): # 工作信息插入
# 3.3 工作信息插入及需求信息 插入/升级
@user_info_extend_blueprint.route('/work_info_insert', methods=['POST'])
def work_info_insert():
    open_id = request.form.get('open_id')
    unit_property = request.form.get('unit_property')
    field = request.form.get('field')
    unit_introduction = request.form.get('unit_introduction')
    competitive_strength = request.form.get('competitive_strength')
    activity_city = request.form.get('activity_city')
    resource = request.form.get('resource')
    help = request.form.get('help')
    recommend_user_openid = request.form.get('recommend_user_id')
    write_status = request.form.get('write_status', default=True, type=bool)

    # Check if the required arguments are present
    if not open_id or not unit_property or not field or not unit_introduction or not competitive_strength or not activity_city or not resource or not help or not recommend_user_openid:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "open_id, unit_property, field, unit_introduction, competitive_strength, activity_city, resource, help, recommend_user_id are required",
            "resultBody": None

        }

        return jsonify(args_error)

    # Check if the user exists in the database
    with PostgreSingleton() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries
        wtm = WxUserTableMethods(conn, cur)

        wx_user_info = wtm.get_user_by_open_id(open_id)

        if not wx_user_info:
            args_error = {
                "status": -1,
                "errorCode": 1002,
                "errorMsg": "recommend_user_openid User not found",
                "resultBody": None
            }

            return jsonify(args_error)
        
        wx_user_id = wx_user_info["user_id"]


        # recommend_user_id = wtm.get_user_by_open_id(recommend_user_openid)["user_id"]
        recommend_user = wtm.get_user_by_open_id(recommend_user_openid)

        if recommend_user:
            recommend_user_id = recommend_user["user_id"]
        else:

            args_error = {
                "status": -1,
                "errorCode": 1002,
                "errorMsg": "Recommend user not found",
                "resultBody": None
            }

            return jsonify(args_error)


        wui = WxUserInfoExtendTableMethods(conn, cur)
        wui.work_info_insert(wx_user_id, unit_property, field, unit_introduction, competitive_strength, activity_city, resource, help, recommend_user_id, write_status)

    result_body = {
        "status": 1,
        "errorCode": None,
        "errorMsg": None,
        "resultBody": "User work info insert success"  
    }

    return jsonify(result_body)
   